# coding = utf-8
# @Time    : 2024-10-29  13:27:52
# @Author  : zhaosheng@nuaa.edu.cn
# @Describe: Utils for customer service evaluation system Version 2.0
# In this file, we'll use Qwen2-Audio to help analyze the audio data.(Emotion recognition, etc.)

import os
import requests
import cfg
# 设置 API 端点
url = cfg.QWEN2AUIO_URL

prompt="""
<任务>
请对提供的音频文件以及说话内容进行综合的情绪分析。根据话者的语调、言辞和情绪表现，综合的判断其当前的情绪状态，并将结果返回为一个 JSON 格式的对象。具体要求如下：
</任务>
<情绪类别>
情绪类别可分为以下几类：
生气
厌恶
恐惧
开心
中立
其他
难过
</情绪类别>
<输出格式>
返回结果格式要求为 JSON 对象，包含一个字段 `emotion`，其值为上述情绪类别之一。如果无法清晰判断情绪类别，请填写“中立”。
</输出格式>
<示例输出>
{
  "emotion": "开心"
}
</示例输出>
"""

prompt_en="""
<Task>
Please perform an emotion analysis on the provided audio file or spoken content.
Based on the speaker's tone, wording, and emotional expression, 
determine their current emotional state and return the result as a JSON object.
Specific requirements are as follows: 
</Task>
<Emotion Categories> The emotion categories can be divided into the following: 
- angry 
- disgusted 
- fearful
- happy 
- neutral 
- other
- sad
- surprised 
</Emotion Categories>
<Output Format>
The result should be returned in the format of a JSON object,
 containing a field `emotion` whose value is one of the above emotion categories. 
 If it is not possible to clearly determine the emotion category, 
 please fill in "Neutral". 
</Output Format>
<Example Output>
{ "emotion": "happy" }
</Example Output>
"""


def analyze_emotion(audio_path,start=0,end=-1,language="en",max_try=3):
    # 示例 1：请求描述语音情绪（本地文件）
    data_local = {
        "text": prompt.replace("\n"," ") if language=="zh" else prompt_en.replace("\n"," "),
        "url": f"local:{audio_path}",
        "start": start,
        "end": end
    }
    while max_try>0:
        try:
            response_local = requests.post(url, json=data_local)
            print(response_local)
            print("Response from local file request:", response_local.json())
            dict_data = response_local.json().get("response")
            dict_data = eval(dict_data)
            label = dict_data.get("emotion")
            return label
        except Exception as e:
            print("Error processing audio from local file: ", str(e))
            max_try -= 1
    return "error"


